<?php

namespace app\admin\controller;

use think\Db;

class WebKey extends Authorized
{

    public function index(){
        $get_data=$this->request->get();
        $webID = $get_data['webID'];
        $this->assign('webID', $webID);


        $sum=Db::table('tb_money')->where(['webid'=>$webID,'keyid'=>['>',0]])->sum('money');
        $sumMonth=Db::table('tb_money')->where(['webid'=>$webID,'keyid'=>['>',0]])->whereTime('intime', 'month')->sum('money');

        $this->assign('sum', $sum);
        $this->assign('sumMonth', $sumMonth);
        return $this->fetch();

    }

    public function getList()
    {
        $get_data=$this->request->get();
        $post_data = $this->request->post();

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $keywords = input('keywords');
        $where=[];

        if (!empty($keywords)){
            $where['name']=['like','%'.$keywords.'%'];
        }
        if (!empty($get_data['webID'])){
            $webID = $get_data['webID'];
            $where['webID']=$webID;
        }

        $count=Db::table('tb_webkey')->where($where)->count();
        $sum=Db::table('tb_webkey')->where($where)->sum('moneypay');
        $rows=Db::table('tb_webkey')->where($where)->order('state,typeid,id desc')->page($page, $limit)->select();
        return json(['code' =>0,'count' =>$count,'totalRow'=>['moneypay'=>$sum],'msg' =>'','data'=>$rows]);
    }

    public function add()
    {
        $get_data = $this->request->get();
        $webID = $get_data['webID'];
        $this->assign('webID', $webID);

        $webinfo=Db::table('tb_webinfo')->where('id',$webID)->find();

        $post_data = $this->request->post();
        if($post_data){
            $content = trim($post_data['content']);//所有关键字

            $str=preg_replace('/\n{2,}|\s{1,}\n|\n\s{1,}/',"\n",$content); //去除多余
            $arr=explode("\n", $str);   //行数分割
            $arrlist=array_filter($arr);         //去掉空数组

//            开始遍历行数
            $msg='';
//sid规则
            $sidrules = array(
                array('typeid'=>1,'sid'=>1010),
                array('typeid'=>2,'sid'=>1015),
                array('typeid'=>3,'sid'=>7010),
                array('typeid'=>4,'sid'=>1030),
                array('typeid'=>5,'sid'=>7070),
            );

            foreach($arrlist as $k=>$v){
                $v=preg_replace("/\s+/",",",$v); //去除多余
                $a=explode(",", $v);

                    $typeid=$a[0];
                    $name=$a[1];
                    $money_one=$a[2];
                    $money_two=$a[3];
                    $sid=0;
                    foreach($sidrules as $r){
                        if($typeid==$r['typeid']){
                            $sid=$r['sid'];
                            break;
                        }
                    }


                $data=['state'=>1,'userid'=>$webinfo['userID'],'webID'=>$webinfo['id'], 'seoid'=>$webinfo['seoid'], 'url'=>$webinfo['url'],
                    'sid'=>$sid,
                    'typeid'=>$typeid,
                    'name'=>$name,'money_one'=>$money_one, 'money_two'=>$money_two
                ];

                $resultNum=Db::table('tb_webkey')->where(['userid'=>$webinfo['userID'],'webID'=>$webinfo['id'],'typeid'=>$typeid, 'name'=>$name])->count();
                if($resultNum==0){
                    $id =Db::table('tb_webkey')->insertGetId($data);
                    if (false === $id) {
                        $msg=$msg.$typeid.' -'.$name.'-添加失败<br>';
                    } else {
                        $api=jqcpm_add($sid,$name,$webinfo['url']);  //提交api库

                        $content = json_decode($api);
                        $yid = $content->tid;

                        $d = [];
                        if(!$yid){
                            $d['tstate'] = 0;
                        }else{
                            $d['ybyid'] = $yid; //更新apiID
                            $d['tstate'] = 1; //加入api库状态
                        }
                        Db::table('tb_webkey')->where(['id' =>$id])->update($d); //更新关键词api数据


                        Db::table('tb_user')->where('id',$webinfo['userID'])->setInc('keyNum'); //用户关键字数量增加
                        Db::table('tb_webinfo')->where('id',$webinfo['id'])->setInc('keyNum'); //网站关键字数量增加
                        $msg=$msg.$typeid.' - '.$name.'-添加成功('.$id.')-'.$api.'<br>';
                    }
                }else{
                    $msg=$msg.$typeid.'-'.$name.'-添加失败(重复)<br>';
                }
            }
            return json(['code' =>1,'count' =>0,'msg' =>$msg,'data'=>'']);
        }

       return $this->fetch();
    }

    public function edit()
    {
        $post_data = $this->request->post();
        if($post_data){
            $id=array_shift($post_data);
            $result =Db::table('tb_webkey')->where('id',$id)->setField($post_data);
            if (false === $result) {
                return json(['msg' =>'失败', 'code' =>1]);
            } else {
                return json(['msg' =>'成功', 'code' =>0]);
            }
        }

        $article=Db::table('tb_webkey')->where('id' , input('id'))->find();
        $this->assign('article', $article);
       return $this->fetch();
    }


//批量启用
    public function set_allUp()
    {
        $post_data = $this->request->post();
        if($post_data){
            $ids1=explode(",", $post_data['ids1']); //正常状态id

            $webID=$post_data['webID'];
            $webinfo=Db::table('tb_webinfo')->where('id',$webID)->find();
            $msg='';
            foreach($ids1 as $k=>$v){
                $keyinfo =Db::table('tb_webkey')->where('id',$v)->find();
//                $msg=$msg.$id['name'].'<br>';
                if (!$keyinfo) {
                    $msg=$msg.'操作失败<br>';
                } else {
                    $api=jqcpm_add($keyinfo['sid'],$keyinfo['name'],$keyinfo['url']);
                    $content = json_decode($api);
                    $yid = $content->tid;

                    $d = [];
                    if(!$yid){
                        $d['state'] = 1;
                        $d['tstate'] = 0;
                    }else{
                        $d['state'] = 1;
                        $d['ybyid'] = $yid; //更新apiID
                        $d['tstate'] = 1; //加入api库状态
                    }
                    Db::table('tb_webkey')->where(['id' =>$keyinfo['id']])->update($d); //更新关键词api数据

                    Db::table('tb_user')->where('id',$webinfo['userID'])->setInc('keyNum');  //更新用户关键词数量
                    Db::table('tb_webinfo')->where('id',$webinfo['id'])->setInc('keyNum');  //更新网站关键词数量

                    $msg=$msg.$keyinfo['sid'].$keyinfo['name'].$keyinfo['url'].'成功<br>';

                }

            }
            return json(['msg' =>$msg, 'code' =>0]);
        }
    }

//批量停用
    public function set_allStop()
    {
        $post_data = $this->request->post();
        if($post_data){
            $ids1=explode(",", $post_data['ids1']); //正常状态id

            $webID=$post_data['webID'];
            $webinfo=Db::table('tb_webinfo')->where('id',$webID)->find();

//更新状态，删除api库
            $result =Db::table('tb_webkey')->whereIn('id',$ids1)->setField(['state'=>3,'tstate'=>0,'ybyid'=>0]);

            if (false === $result) {
                return json(['msg' =>'操作失败', 'code' =>1]);
            } else {
                Db::table('tb_user')->where('id',$webinfo['userID'])->update(['keyNum'=>Db::raw('keyNum-'.$result)]);  //更新用户关键词数量
                Db::table('tb_webinfo')->where('id',$webinfo['id'])->update(['keyNum'=>Db::raw('keyNum-'.$result)]);  //更新网站关键词数量
                return json(['msg' =>'操作成功', 'code' =>0,'data'=>$result]);

            }
        }
    }

//批量删除（数量更新出，停用网站也算数量）
    public function all_del()
    {
        $post_data = $this->request->post();
        if($post_data){

            $ids1=explode(",", $post_data['ids1']); //正常状态id
            $ids2=explode(",", $post_data['ids2']);// 不改变数量id
            $webID=$post_data['webID'];

            $result =Db::table('tb_webkey')->whereIn('id',$ids1)->delete();
            $result2 =Db::table('tb_webkey')->whereIn('id',$ids2)->delete();

            if (false === $result && false === $result2) {
                return json(['msg' =>'删除失败', 'code' =>1]);
            } else {
                $webinfo=Db::table('tb_webinfo')->where('id',$webID)->find();
                Db::table('tb_user')->where('id',$webinfo['userID'])->update(['keyNum'=>Db::raw('keyNum-'.$result)]);  //更新用户关键词数量
                Db::table('tb_webinfo')->where('id',$webinfo['id'])->update(['keyNum'=>Db::raw('keyNum-'.$result)]);  //更新网站关键词数量
                return json(['msg' =>'删除成功', 'code' =>0,'data'=>$result]);

            }
        }
    }



//改变状态
    public function set_state()
    {
        $post_data = $this->request->post();
        if($post_data){
            $d=[];
            $update=[];
            if ($post_data['state']==3){
                $d['state']=3;
                $d['tstate']=0;
                $d['ybyid']=0;

                $update['keyNum']=Db::raw('keyNum-1');
            }
            if($post_data['state']==1) {
                $d['state']=1;
                $update['keyNum']=Db::raw('keyNum+1');
            }

            Db::table('tb_webkey')->startTrans();
            //更新状态
            $result =Db::table('tb_webkey')->where('id', $post_data['id'])->update($d);

            if (false === $result) {
                Db::table('tb_webkey')->rollback();
                return json(['code' =>1,'count' =>0,'msg' =>'失败','data'=>'']);
            } else {
                Db::table('tb_webkey')->commit();
                $res=Db::table('tb_webkey')->where('id',$post_data['id'])->find();

                Db::table('tb_user')->where('id',$res['userid'])->update($update);  //更新用户关键词数量
                Db::table('tb_webinfo')->where('id',$res['webID'])->update($update);  //更新网站关键词数量

                return json(['code' =>0,'count' =>0,'msg' =>'成功','data'=>'']);
            }

        }
    }


    public function del()
    {
        $post_data = $this->request->post();
        if($post_data){
            $result =Db::table('tb_webkey')->where('id', $post_data['id'])->delete();
            if (false === $result) {
                return json(['msg' =>'删除失败', 'code' =>1]);
            } else {
                return json(['msg' =>'删除成功', 'code' =>0]);
            }
        }
    }
}